package com.xiaohong.oauth.config;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyClientDetailsService implements ClientDetailsService {
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        System.out.println("clientId = " + clientId);
        // 实际使用时，这里增加读数据库的操作，根据clientId获取账户信息，并根据下面代码的方式生成BaseClientDetails对象即可

        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId("clientapp");
        // secret密码配置从 Spring Security 5.0开始必须以 {加密方式}+加密后的密码 这种格式填写
        /*
         *   当前版本5新增支持加密方式：
         *   bcrypt - BCryptPasswordEncoder (Also used for encoding)
         *   ldap - LdapShaPasswordEncoder
         *   MD4 - Md4PasswordEncoder
         *   MD5 - new MessageDigestPasswordEncoder("MD5")
         *   noop - NoOpPasswordEncoder
         *   pbkdf2 - Pbkdf2PasswordEncoder
         *   scrypt - SCryptPasswordEncoder
         *   SHA-1 - new MessageDigestPasswordEncoder("SHA-1")
         *   SHA-256 - new MessageDigestPasswordEncoder("SHA-256")
         *   sha256 - StandardPasswordEncoder
         */
        baseClientDetails.setClientSecret("{noop}112233");

        // 不可以设置为null
       // baseClientDetails.setAutoApproveScopes(null);

        List<String> scopeList = new ArrayList<>();
        scopeList.add("read_userinfo");
        scopeList.add("read_contacts");
        baseClientDetails.setScope(scopeList);

        baseClientDetails.setResourceIds(null);

        List<String> grantTypeList = new ArrayList<>();
        grantTypeList.add("client_credentials");
        // 运行刷新token
        grantTypeList.add("refresh_token");
        baseClientDetails.setAuthorizedGrantTypes(grantTypeList);
        baseClientDetails.setRegisteredRedirectUri(Sets.newHashSet());
        // 不可以设置为null
        // baseClientDetails.setAuthorities(null);
        // 设置accessToken和refreshToken有效期
        baseClientDetails.setAccessTokenValiditySeconds(1000);
        baseClientDetails.setRefreshTokenValiditySeconds(1000);
        baseClientDetails.setAdditionalInformation(Maps.newHashMap());
        return baseClientDetails;
    }
}
